<template>
  <div class="post-editor">
    <div class="editor-header">
      <h2>{{ dialogTitle }}</h2>
      <el-button type="text" @click="closeEditor">
        <el-icon><Close /></el-icon>
      </el-button>
    </div>

    <div class="editor-content">
      <!-- 内容输入 -->
      <div class="content-section">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="6"
          placeholder="分享你的想法、经验或需求..."
          resize="none"
          maxlength="2000"
          show-word-limit
          class="content-input"
        />
      </div>

      <!-- 关键词标签 -->
      <div class="keywords-section">
        <div class="section-header">
          <h4>添加关键词</h4>
          <span class="tip">（输入关键词后按回车添加）</span>
        </div>
        <div class="keywords-input">
          <el-input
            v-model="keywordInput"
            placeholder="输入关键词"
            @keyup.enter="addKeyword"
            clearable
          >
            <template #append>
              <el-button @click="addKeyword">添加</el-button>
            </template>
          </el-input>
        </div>
        <div class="keywords-list">
          <el-tag
            v-for="(keyword, index) in formData.keywords"
            :key="index"
            closable
            type="info"
            size="large"
            @close="removeKeyword(index)"
            class="keyword-tag"
          >
            #{{ keyword }}
          </el-tag>
        </div>
      </div>

      <!-- 图片上传 -->
      <div class="images-section">
        <div class="section-header">
          <h4>添加图片</h4>
          <span class="tip">（最多上传 9 张图片）</span>
        </div>
        
        <div class="images-upload">
          <!-- 上传按钮 -->
          <div
            v-if="formData.images.length < 9"
            class="upload-btn"
            @click="triggerFileInput"
          >
            <el-icon size="24"><Plus /></el-icon>
            <span>添加图片</span>
            <input
              ref="fileInput"
              type="file"
              multiple
              accept="image/*"
              @change="handleImageUpload"
              style="display: none"
            />
          </div>

          <!-- 图片预览 -->
          <div
            v-for="(image, index) in formData.images"
            :key="index"
            class="image-preview"
          >
            <img :src="image.url || image" :alt="`图片 ${index + 1}`" />
            <div class="image-actions">
              <el-button
                type="danger"
                size="small"
                circle
                @click="removeImage(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 帖子类型 -->
      <div class="post-type-section">
        <div class="section-header">
          <h4>帖子类型</h4>
        </div>
        <el-radio-group v-model="formData.type">
          <el-radio label="farmer">农夫帖子</el-radio>
          <el-radio label="buyer">买家帖子</el-radio>
        </el-radio-group>
      </div>

      <!-- 隐私设置 -->
      <div class="privacy-section">
        <div class="section-header">
          <h4>隐私设置</h4>
        </div>
        <el-radio-group v-model="formData.privacy">
          <el-radio label="public">公开（所有人可见）</el-radio>
          <el-radio label="private">仅自己可见</el-radio>
        </el-radio-group>
      </div>
    </div>

    <div class="editor-footer">
      <div class="footer-actions">
        <el-button @click="closeEditor">取消</el-button>
        <el-button
          type="primary"
          @click="submitPost"
          :loading="submitting"
          :disabled="!canSubmit"
        >
          {{ isEdit ? '更新帖子' : '发布帖子' }}
        </el-button>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="showImagePreview"
      title="图片预览"
      width="600px"
      align-center
    >
      <div class="image-preview-dialog">
        <img :src="previewImageUrl" alt="预览图片" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  // 当前用户信息
  currentUser: {
    type: Object,
    required: true
  },
  // 编辑的帖子数据
  editPostData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['close', 'submit'])

// 响应式数据
const formData = ref({
  content: '',
  keywords: [],
  images: [],
  type: 'farmer',
  privacy: 'public'
})
const keywordInput = ref('')
const submitting = ref(false)
const showImagePreview = ref(false)
const previewImageUrl = ref('')
const fileInput = ref(null)

// 计算属性
const isEdit = computed(() => !!props.editPostData)
const canSubmit = computed(() => {
  return formData.value.content.trim().length > 0 && !submitting.value
})
const dialogTitle = computed(() => isEdit.value ? '编辑帖子' : '发布新帖子')

// 监听编辑数据变化，回显数据
watch(() => props.editPostData, (newVal) => {
  if (newVal) {
    // 回显编辑数据
    formData.value = {
      content: newVal.content || '',
      keywords: newVal.keywords ? [...newVal.keywords] : [],
      images: newVal.images ? newVal.images.map(img => ({ url: img })) : [],
      type: newVal.type || 'farmer',
      privacy: newVal.privacy || 'public'
    }
  }
}, { immediate: true })

// 添加关键词
const addKeyword = () => {
  const keyword = keywordInput.value.trim()
  if (keyword && !formData.value.keywords.includes(keyword)) {
    formData.value.keywords.push(keyword)
    keywordInput.value = ''
  }
}

// 移除关键词
const removeKeyword = (index) => {
  formData.value.keywords.splice(index, 1)
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理图片上传
const handleImageUpload = (event) => {
  const files = Array.from(event.target.files)
  const remainingSlots = 9 - formData.value.images.length
  
  if (files.length > remainingSlots) {
    ElMessage.warning(`最多只能上传 ${remainingSlots} 张图片`)
    files.splice(remainingSlots)
  }

  files.forEach(file => {
    if (!file.type.startsWith('image/')) {
      ElMessage.warning('请上传图片文件')
      return
    }

    if (file.size > 5 * 1024 * 1024) {
      ElMessage.warning('图片大小不能超过 5MB')
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      formData.value.images.push({
        url: e.target.result,
        file: file
      })
    }
    reader.readAsDataURL(file)
  })

  // 清空 input，允许重复选择相同文件
  event.target.value = ''
}

// 移除图片
const removeImage = (index) => {
  formData.value.images.splice(index, 1)
}

// 预览图片
const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  showImagePreview.value = true
}

// 关闭编辑器
const closeEditor = () => {
  if (formData.value.content.trim() || formData.value.keywords.length > 0 || formData.value.images.length > 0) {
    ElMessageBox.confirm(
      '您有未保存的内容，确定要离开吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      resetForm()
      emit('close')
    }).catch(() => {
      // 用户取消操作，不做任何处理
    })
  } else {
    resetForm()
    emit('close')
  }
}

// 提交帖子
const submitPost = async () => {
  if (!canSubmit.value) return

  submitting.value = true

  try {
    // 准备提交数据
    const submitData = {
      content: formData.value.content.trim(),
      keywords: formData.value.keywords,
      images: await processImages(),
      type: formData.value.type,
      privacy: formData.value.privacy,
      author: {
        id: props.currentUser.id,
        name: props.currentUser.name,
        avatar: props.currentUser.avatar,
        type: props.currentUser.type
      }
    }

    // 如果是编辑模式，保留原帖子的ID
    if (isEdit.value) {
      submitData.id = props.editPostData.id
    }

    // 发射提交事件
    emit('submit', submitData)

    // 显示成功消息
    ElMessage.success(isEdit.value ? '帖子更新成功' : '帖子发布成功')

    // 重置表单
    resetForm()

    // 延迟关闭，让用户看到成功消息
    setTimeout(() => {
      emit('close')
    }, 1500)

  } catch (error) {
    console.error('提交帖子失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 处理图片上传（模拟）
const processImages = async () => {
  const imageUrls = []
  
  for (const image of formData.value.images) {
    if (image.file) {
      // 模拟图片上传到服务器
      const uploadedUrl = await simulateImageUpload(image.file)
      imageUrls.push(uploadedUrl)
    } else {
      // 使用已有URL（编辑模式）
      imageUrls.push(image.url || image)
    }
  }
  
  return imageUrls
}

// 模拟图片上传
const simulateImageUpload = (file) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 在实际项目中，这里应该是真实的图片上传逻辑
      // 返回一个模拟的图片URL
      resolve(URL.createObjectURL(file))
    }, 500)
  })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    content: '',
    keywords: [],
    images: [],
    type: props.currentUser.type || 'farmer',
    privacy: 'public'
  }
  keywordInput.value = ''
}

// 初始化
const initEditor = () => {
  if (props.editPostData) {
    // 编辑模式：回显数据
    formData.value = {
      content: props.editPostData.content || '',
      keywords: props.editPostData.keywords ? [...props.editPostData.keywords] : [],
      images: props.editPostData.images ? props.editPostData.images.map(img => ({ url: img })) : [],
      type: props.editPostData.type || 'farmer',
      privacy: props.editPostData.privacy || 'public'
    }
  } else {
    // 新建模式：重置表单
    resetForm()
  }
}

// 组件挂载时初始化
nextTick(() => {
  initEditor()
})
</script>

<style scoped>
.post-editor {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 90vh;
}

.editor-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
  border-radius: 12px 12px 0 0;
}

.editor-header h2 {
  margin: 0;
  color: #1f2937;
  font-size: 1.25rem;
  font-weight: 600;
}

.editor-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.content-section {
  margin-bottom: 24px;
}

.content-input {
  font-size: 1rem;
  line-height: 1.6;
}

.content-input :deep(.el-textarea__inner) {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  font-size: 1rem;
  line-height: 1.6;
  transition: border-color 0.3s;
}

.content-input :deep(.el-textarea__inner:focus) {
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  color: #374151;
  font-size: 0.875rem;
  font-weight: 600;
}

.tip {
  color: #6b7280;
  font-size: 0.75rem;
}

.keywords-section,
.images-section,
.post-type-section,
.privacy-section {
  margin-bottom: 24px;
}

.keywords-input {
  margin-bottom: 12px;
}

.keywords-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.keyword-tag {
  background: linear-gradient(135deg, #fef7ed, #fed7aa);
  border-color: #fdba74;
  color: #9a3412;
  font-weight: 500;
  transition: all 0.3s ease;
}

.keyword-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.images-upload {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
}

.upload-btn {
  height: 120px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #6b7280;
}

.upload-btn:hover {
  border-color: #4caf50;
  color: #4caf50;
  background: #f8fafc;
}

.image-preview {
  position: relative;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-preview img:hover {
  transform: scale(1.05);
}

.image-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

.post-type-section :deep(.el-radio-group),
.privacy-section :deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.post-type-section :deep(.el-radio),
.privacy-section :deep(.el-radio) {
  margin-right: 0;
}

.editor-footer {
  padding: 20px 24px;
  border-top: 1px solid #e5e7eb;
  background: #f8fafc;
  border-radius: 0 0 12px 12px;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.image-preview-dialog {
  text-align: center;
}

.image-preview-dialog img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-editor {
    margin: 0;
    border-radius: 0;
    max-height: 100vh;
  }

  .editor-content {
    padding: 16px;
  }

  .editor-header,
  .editor-footer {
    padding: 16px;
  }

  .images-upload {
    grid-template-columns: repeat(3, 1fr);
  }

  .upload-btn,
  .image-preview {
    height: 100px;
  }
}

@media (max-width: 480px) {
  .images-upload {
    grid-template-columns: repeat(2, 1fr);
  }

  .upload-btn,
  .image-preview {
    height: 80px;
  }
}
</style>